# -*- coding: utf-8 -*-
"""
Created on Sat Jul  1 15:27:19 2017

@author: claude
"""
import pymongo

class MongoClint():
    collection_item = 'users'
    def __init__(self):
        self.client = pymongo.MongoClient('localhost', 27017)
        self.db = self.client.weidian
    def go_over_all_orders(self):
        return mongodb.db.orders.find()
    def find_user(self, user_phone):
        if (self.db[self.collection_item].find_one({"_id" : user_phone}))==None:
            return False
        else:
            return True
    def push_user_orders(self, user_id, order_id):
        self.db[self.collection_item].update({"_id":user_id},{"$push":{"order":order_id}})
    def save_item_to_db(self, item):
        try:
            self.db[self.collection_item].insert(item)
        except pymongo.errors.DuplicateKeyError:
            print '_id %s has been existed', item["_id"]
            
if __name__=="__main__":
    mongodb = MongoClint()
    for x in mongodb.go_over_all_orders():
        user = x['result']['buyer_info']
        user['_id'] = x['result']['user_phone']
        user['order'] = [x['result']['order_id']]
        if mongodb.find_user(user['_id'])==True:
            mongodb.push_user_orders(user['_id'], user['order'])
        else:
            mongodb.save_item_to_db(user)
            
                